//引入api 请求数据
// 到底是谁,没有引用vuex却用vuex的配置在这写东西,这个模块貌似压根没用上
import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken, getRoles, setRoles, getUsername, setUsername, getLoginlogid, setUsercode } from '@/utils/auth'
export default {
  state: () => ({
    token: getToken(),
    name: '',
    roles: getRoles() || [],
    username: getUsername() || '',
    password: '',
    loginlogid: getLoginlogid() || '',
  }),
  getters: {
    gettersUserInfos(state) {
      if (!state.userInfos) {
        let userInfo = localStorage.getItem("userInfos")
        if (userInfo && userInfo != "null") {
          userInfo = JSON.parse(userInfo)
        }
        state.userInfos = userInfo
      }
      return state.userInfos
    }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_LOGINLOGID: (state, loginlogid) => {
      state.loginlogid = loginlogid
    },
    // SET_PASSWORD: (state, password) => {
    //   state.password = password
    // }

  },
  //异步方法 Action 可以包含任意异步操作
  actions: {
    // user login
    login({ commit }, userInfo) {
      // const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ user: userInfo }).then(response => {
          const { Result } = response
          commit('SET_TOKEN', Result.Token)
          commit('SET_ROLES', Result.data)
          commit('SET_USERNAME', Result.UserName)
          commit('SET_LOGINLOGID', Result.loginlogid)
          // commit('SET_PASSWORD', password)
          setToken(Result.Token)
          setRoles(Result.data)
          setUsername(Result.UserName)
          setUsercode(Result.UserID);
          setLoginlogid(Result.loginlogid)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // user logout
    logout({ commit, state }) {
      var params = {
        Token: state.token,
        loginlogid: state.loginlogid
      }
      return new Promise((resolve, reject) => {
        logout(params).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_USERNAME', '')
          commit('SET_LOGINLOGID', '')
          // commit('SET_PASSWORD', '')
          removeToken()
          removeLoginlogid()
          resetRouter()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  },

}